15.7 Memory Compaction
As the operating system executes continuous runtime allocations and deallocations, physical memory inevitably fragments into heavily atomized address blocks, which severely degrades instruction processing execution velocity. To counteract this bottleneck, Linux implements a memory compaction infrastructure designed to defragment physical pages and maximize the sizing footprints of contiguous memory blocks. During the system bootstrap phase, Linux triggers a dedicated background memory compaction daemon to continuously optimize the memory pools asynchronously. Furthermore, when the core page allocator __alloc_pages() encounters large multi-page allocation requests, it can synchronously invoke memory compaction routines to harvest larger continuous blocks of free space. Linux additionally implements explicit system call entry points enabling users to manually trigger memory compaction passes from user space.
The definitive workload of memory compaction is orchestrated by the function compact_zone(). This routine first invokes isolate_migratepages() to scan an architectural memory zone (struct zone), isolate any eligible movable pages discovered within it, and aggregate these isolated page components inside a compaction control block (struct compact_control) to prepare for subsequent migration blocks. Programmatically, page isolation is achieved by setting the PG_isolated bit flag inside the flags field of the corresponding struct page descriptor, which restricts other concurrent execution contexts from manipulating these pages. Upon successfully isolating the target migration candidate blocks, compact_zone() leverages the callback wrapper compaction_alloc() to isolate a series of free pages from the zone's internal free_list structures, carves out appropriate destination tracking frames from this isolated free pool, and then calls migrate_pages() to physically relocate the payload data from the isolated movable pages over into the newly allocated free page blocks. By physically shifting these movable pages, the compaction engine consolidates fragmented, scattered blocks together to generate a single unified, physically contiguous memory asset.